package org.springleaf.core.mvc.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springleaf.core.mvc.dao.BaseDao;

/**
 * 简单的数据操作类
 * @author leaf
 *
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class SimpleBaseDaoImpl extends HibernateDaoSupport implements BaseDao {
	
    @Override
	public void delete(Object obj) {
		this.getHibernateTemplate().delete(obj);
	}

	@Override
	public <T>T get(Class<T> classz,Serializable id) {
		return (T) this.getHibernateTemplate().get(classz, id);
	}

	@Override
	public Object save(Object obj) {
		return this.getHibernateTemplate().save(obj);
	}

	@Override
	public void update(Object obj) {
		this.getHibernateTemplate().update(obj);
	}

	@Override
	public void initialize(Object obj) {
		this.getHibernateTemplate().initialize(obj);
	}
	

	public Query getQuery(String hql, Object[] params) {
		Query query = this.getSession().createQuery(hql);
		if (params != null) {
			for (int i = 0; i < params.length; i++) {
				query.setParameter(i, params[i]);
			}
		}
		return query;
	}

	@Override
	public void executeUpdate(String hql, Object[] params) {
		getQuery(hql, params).executeUpdate();
	}

	@Override
	public List query(String hql, Object[] params) {
		return getQuery(hql, params).list();
	}

	@Override
	public List queryAsRow(String hql, int start, int maxSize, Object[] params) {
		return getQuery(hql, params).setFirstResult(start)
				.setMaxResults(maxSize).list();
	}

	@Override
	public Object get(String hql, Object[] params) {
		List list = this.query(hql, params);
		return list.size() > 0 ? list.get(0) : null;
	}

	@Override
	public SessionFactory getSessionFacotry() {
		return super.getSessionFactory();
	}
}
